package thread2;

import trees.TreeNode;

import java.util.*;

public class Solution2 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);

        Stack<List<Integer>> result = new Stack<>();
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node != null) {
                    temp.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }

                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
            }

            result.push(temp);
        }

        List<List<Integer>> newResult = new ArrayList<>();

        while (!result.isEmpty()) {
            List<Integer> temp = result.pop();
            newResult.add(temp);
        }

        return newResult;
    }

    public static void main(String[] args) {
        // 构造树
        TreeNode treeNode = new TreeNode(3);
        treeNode.left = new TreeNode(9);
        treeNode.right = new TreeNode(20);
        treeNode.right.left = new TreeNode(15);
        treeNode.right.right = new TreeNode(7);

        Solution2 solution = new Solution2();
        List<List<Integer>> result = solution.levelOrderBottom(treeNode);
        result.forEach(item -> {
            for (Integer integer : item) {
                System.out.print(integer + "\t");
            }
            System.out.println();
        });
    }
}
